package controller

import (
	"intelli-dl-online-logo-go/service"
	"intelli-dl-online-logo-go/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

type VerifyController struct {
	verifyService service.VerifyService
}

func NewVerifyController(verifyService service.VerifyService) *VerifyController {
	return &VerifyController{verifyService: verifyService}
}

// GetSMSCode 获取手机验证码
func (vc *VerifyController) GetSMSCode(c *gin.Context) {
	phone := c.Query("phone")
	if phone == "" {
		c.JSON(http.StatusBadRequest, utils.ErrorResponse("手机号不能为空"))
		return
	}

	err := vc.verifyService.SendSMSCode(phone)
	if err != nil {
		c.JSON(http.StatusInternalServerError, utils.ErrorResponse(err.Error()))
		return
	}

	c.JSON(http.StatusOK, utils.SuccessResponse(nil))
}

// GetEmailCode 获取邮箱验证码
func (vc *VerifyController) GetEmailCode(c *gin.Context) {
	email := c.Query("email")
	if email == "" {
		c.JSON(http.StatusBadRequest, utils.ErrorResponse("邮箱不能为空"))
		return
	}

	err := vc.verifyService.SendEmailCode(email)
	if err != nil {
		c.JSON(http.StatusInternalServerError, utils.ErrorResponse(err.Error()))
		return
	}

	c.JSON(http.StatusOK, utils.SuccessResponse(nil))
}

// VerifySMSCode 验证手机验证码
func (vc *VerifyController) VerifySMSCode(c *gin.Context) {
	phone := c.Query("phone")
	code := c.Query("code")
	if phone == "" || code == "" {
		c.JSON(http.StatusBadRequest, utils.ErrorResponse("手机号和验证码不能为空"))
		return
	}

	valid, err := vc.verifyService.VerifySMSCode(phone, code)
	if err != nil {
		c.JSON(http.StatusInternalServerError, utils.ErrorResponse(err.Error()))
		return
	}

	if !valid {
		c.JSON(http.StatusOK, utils.ErrorResponse("验证码错误或已过期"))
		return
	}

	c.JSON(http.StatusOK, utils.SuccessResponse(nil))
}

// VerifyEmailCode 验证邮箱验证码
func (vc *VerifyController) VerifyEmailCode(c *gin.Context) {
	email := c.Query("email")
	code := c.Query("code")
	if email == "" || code == "" {
		c.JSON(http.StatusBadRequest, utils.ErrorResponse("邮箱和验证码不能为空"))
		return
	}

	valid, err := vc.verifyService.VerifyEmailCode(email, code)
	if err != nil {
		c.JSON(http.StatusInternalServerError, utils.ErrorResponse(err.Error()))
		return
	}

	if !valid {
		c.JSON(http.StatusOK, utils.ErrorResponse("验证码错误或已过期"))
		return
	}

	c.JSON(http.StatusOK, utils.SuccessResponse(nil))
}
